const express = require('express');
const router = express.Router();
const userModel = require('../model/users'); //查询model
const loginModel = require('../model/login'); //查询model
const multer = require('multer');

const request = require('request');
const sha1 = require('sha1');

const config = require('../config/config'); //配置文件
const util = require('../common/util');

const upload = multer({ //上传模块
  dest: 'uploads/'
})
const waterfall = require('async/waterfall') //瀑布流异步模块
const NodeCache = require('node-cache') //缓存模块
const cache = new NodeCache({
  stdTTL: 3600,
  checkperiod: 3600
}) //3600秒后过过期


// 主页    
router.get('/', async function (req, res, next) {
  const sign = await loginModel.checkSid(req.session.isLogin)
  console.log(sign,'aaa')
  if (sign) { //检查用户是否已经登录
    // console.log(req.session); //打印session的值
    res.render('index', {
      title: 'Express'
    });
  } else { //否则展示index页面
    res.redirect('/login')
  }

});
/* GET home page. */
router.get('/upload1', function (req, res, next) {
  res.render('upload1', {
    title: 'Express'
  });
});
/**
 * 登录
 */
router.get('/login', function (req, res, next) {
  res.render('login', {
    title: '登录'
  });
});
/**
 * 注册
 */
router.get('/register',function(req,res,next){
    res.render('register',{
      title:'注册'
    })
})
router.get('/register1',function(req,res,next){
  res.render('register1',{
    title:'注册'
  })
})
router.get('/api/useRegister',function(req,res,next){
  res.render('return',{
    title:'222'
  })
  // res.json({
  //   code:1
  // })
  console.info(1)
})
/**
 * 微信公众号
 */
router.get('/node', function (req, res, next) {
  res.render('node', {
    title: 'Node'
  });
});
/**
 * 上传文件1
 */
router.get('/upload', function (req, res, next) {
  res.render('upload', {
    title: 'Node'
  });
});
/**
 * 查询列表
 */
router.get('/userLists', function (req, res, next) {
  userModel.userLists(req, res, next)
});

/**
 * 上传文件
 */
var cpUpload = upload.fields([{
  name: 'upload_file',
  maxCount: 1
}, {
  name: 'gallery',
  maxCount: 8
}])

router.post('/profile', cpUpload, function (req, res, next) {
  // req.file 是 `avatar` 文件的信息
  // req.body 将具有文本域数据，如果存在的话
  console.log(req.body)
  console.log(req.file)
  res.status(200)
  res.json({
    code: 0,
    data: {
      aaa: 1
    }
  })
})

/**
 * JS-SDK后端接口
 */
router.post('/wxJssdk/getJssdk', (req, res) => {
  console.log(req.body.url)
  const grant_type = 'client_credential'
  const appid = config.wechat.appID
  const secret = config.wechat.appsecret
  let steps = []
  // 第一步，获取access_token
  steps.push((cb) => {

    let steps1 = []

    // 第1.1步，从缓存中读取access_token
    steps1.push((cb1) => {
      let access_token = cache.get('access_token', (err, access_token) => {
        cb1(err, access_token)
      })
    })

    // 第1.2步，缓存中有access_token则直接返回，如果没有，则从服务器中读取access_token
    steps1.push((access_token, cb1) => {
      if (access_token) {
        cb1(null, access_token, 'from_cache')
      } else {
        request('https://api.weixin.qq.com/cgi-bin/token?grant_type=' + grant_type + '&appid=' + appid + '&secret=' + secret, (err, response, body) => {
          cb1(err, JSON.parse(body).access_token, 'from_server')
        })
      }
    })

    // 第1.3步，如果是新从服务器取的access_token，则缓存起来，否则直接返回
    steps1.push((access_token, from_where, cb1) => {
      if (from_where === 'from_cache') {
        console.log(' === 成功从缓存中读取access_token: ' + access_token + ' ===')
        cb1(null, access_token)
      } else if (from_where === 'from_server') {
        cache.set('access_token', access_token, (err, success) => {
          if (!err && success) {
            console.log(' === 缓存已过期，从服务器中读取access_token: ' + access_token + ' ===')
            cb1(null, access_token)
          } else {
            cb1(err || 'cache设置access_token时，出现未知错误')
          }
        })
      } else {
        cb1('1.3获取from_where时，from_where值为空')
      }
    })



    waterfall(steps1, (err, access_token) => {
      cb(err, access_token)
    })
  })

  // 第二步，获取ticket
  steps.push((access_token, cb) => {
    let steps1 = []

    // 第2.1步，从缓存中读取ticket
    steps1.push((cb1) => {
      let ticket = cache.get('ticket', (err, ticket) => {
        cb1(err, ticket)
      })
    })

    // 第2.2步，缓存中有ticket则直接返回，如果没有，则从服务器中读取ticket
    steps1.push((ticket, cb1) => {
      if (ticket) {
        cb1(null, ticket, 'from_cache')
      } else {
        request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + access_token + '&type=jsapi', (err, response, body) => {
          cb1(err, JSON.parse(body).ticket, 'from_server')
        })
      }
    })

    // 第2.3步，如果新从服务器取的ticket，则缓存起来，否则直接返回
    steps1.push((ticket, from_where, cb1) => {
      if (from_where === 'from_cache') {
        console.log(' === 成功从缓存中读取ticket: ' + ticket + ' ===')
        cb1(null, ticket)
      } else if (from_where === 'from_server') {
        cache.set('ticket', ticket, (err, success) => {
          if (!err && success) {
            console.log(' === 缓存已过期，从服务器中读取ticket: ' + ticket + ' ===');
            cb1(null, ticket)
          } else {
            cb1(err || 'cache设置ticket时，出现未知错误')
          }
        })
      } else {
        cb1('2.3获取from_where时，from_where值为空')
      }
    })

    waterfall(steps1, (err, ticket) => {
      cb(err, ticket)
    })
  })

  // 第三步，生成签名
  steps.push((ticket, cb) => {
    let jsapi_ticket = ticket
    let nonce_str = util.createNonceStr()
    let timestamp = util.createTimestamp()
    let url = req.body.url

    let str = 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + nonce_str + '&timestamp=' + timestamp + '&url=' + url
    let signature = sha1(str)

    cb(null, {
      appId: appid,
      timestamp: timestamp,
      nonceStr: nonce_str,
      signature: signature,
      ticket: ticket
    })
  })
  waterfall(steps, (err, data) => {
    if (err) {
      res.send({
        status: 'error',
        data: err
      })
    } else {
      res.send({
        status: 'success',
        data: data
      })
    }
  })

})


module.exports = router;